<template>
    <gui-popup ref="popup" position="bottom">
        <view v-if="title" class="gui-bg-white gui-padding gui-text-center gui-text gui-border-b">
            {{title}}
        </view>
        <view class="gui-schedule-wrap gui-bg-white gui-padding">
            <view class="gui-flex gui-row gui-space-between gui-align-items-center">
                <picker mode="date" :value="currentDayIn" :start="startDateToday" :end="endDate" @change="selectDate">
                    <text class="gui-schedule-header-date gui-icons gui-primary-text">{{cYear}} 年
                        {{cMonthStr}}
                        月
                        &#xe603;</text>
                </picker>
                <view class="gui-flex gui-row">
                    <text class="gui-border gui-schedule-today gui-secondary-text" @tap="prevMonth" >上月</text>
                    <text class="gui-border gui-schedule-today gui-secondary-text" @tap="nextMonth" >下月</text>
                    <text class="gui-border gui-schedule-today gui-secondary-text" @tap="gotoToday">返回今天</text>
                </view>
            </view>
            <view class="gui-flex gui-row gui-nowrap">
                <text class="gui-schedule-weeks gui-color-gray gui-block" v-for="(item, index) in weeks"
                      :key="index">{{item}}</text>
            </view>
            <view class="gui-flex gui-row gui-wrap">
                <view class="gui-schedule-7item gui-flex gui-row gui-justify-content-center"
                      v-for="(item, index) in days" :key="index">
                    <view v-if="item != ''" class="gui-date-ditems gui-flex gui-columns gui-justify-content-center"
                          :class="[
                              currentDayIn == cYear + '-' + cMonthStr + '-' + item.date? 'gui-bg-primary' : item.flag? 'gui-bg-green' : (cYear + '-' + cMonthStr + '-' + item.date) < today? 'gui-disabled-date' : 'gui-bg-gray gui-dark-bg-level-3'
                          ]"
                          :style="{ pointerEvents: (cYear + '-' + cMonthStr + '-' + item.date) < today? 'none' : 'auto' }"
                          @click="(cYear + '-' + cMonthStr + '-' + item.date) >= today? chooseDate(cYear + '-' + cMonthStr + '-' + item.date, item.date) : null">
                        <text class="gui-date-day gui-block" :class="[
                            currentDayIn == (cYear + '-' + cMonthStr + '-' + item.date)? 'gui-color-white' : item.flag? 'gui-color-white' : (cYear + '-' + cMonthStr + '-' + item.date) < today? 'gui-disabled-date-text' : 'gui-primary-text'
                        ]">{{item.date}}</text>
                        <text class="gui-date-nl gui-block" v-if="isLunar" :class="[
                            currentDayIn == (cYear + '-' + cMonthStr + '-' + item.date)? 'gui-color-white' : item.flag? 'gui-color-white' : (cYear + '-' + cMonthStr + '-' + item.date) < today? 'gui-disabled-date-text' : 'gui-primary-text'
                        ]">{{item.nl}}</text>
                        <view class="gui-schedule-point" v-if="item.haveSe" :style="{backgroundColor:pointColor}">
                        </view>
                    </view>
                    <view class="gui-date-ditems" v-else></view>
                </view>
            </view>

            <view>
                <picker-view @change="changeTime" :value="timeVal" style="height: 300rpx;"
                             indicator-class="picker-column">
                    <picker-view-column>
                        <view class="picker-column" v-for="h in 24" :key="h">
                            {{(h-1)<10?'0' + (h-1):h-1}} 时
                        </view>
                    </picker-view-column>
                    <picker-view-column>
                        <view class="picker-column" v-for="m in 60" :key="m">
                            {{(m-1)<10?'0' + (m-1):m-1}} 分
                        </view>
                    </picker-view-column>
                </picker-view>
            </view>
            <!-- <gui-datetime-bt-base :value="timeVal" @change="changeTime" :isDate="false" :isDay="false"
                                  :isSecond="false"></gui-datetime-bt-base> -->
        </view>
        <view class="gui-padding gui-bg-white">
            <button @tap.stop="confirm()" type="default" class="gui-button gui-bg-red gui-noborder"
                    style="border-radius:50rpx;">
                <text class="gui-color-white gui-button-text">确定</text>
            </button>
        </view>
        <gui-iphone-bottom :customClass="['gui-bg-white', 'gui-dark-bg-level-3']"></gui-iphone-bottom>
    </gui-popup>
</template>

<script>
import moment from "moment";
import guiCalendar from "@/Grace6/js/gui-calendar.js";
export default {
    name: "hyb-calendar-popup",

    props: {
        title: {
            type: String,
            default: ''
        },
        modelValue: {
            type: String,
            default: ""
        }
    },
    data() {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const todayStr = `${year}-${month}-${day}`;
        return {
            timeVal: [7, 0], // 默认时间为早上 7 点
            cYear: 2020,
            cMonth: 1,
            cDay: 10,
            cMonthStr: '01',
            weeks: ['一', '二', '三', '四', '五', '六', '日'],
            days: [],
            currentDayIn: '',
            currentDate: "",
            isLunar: true,
            startDate: '1950-01-01',
            endDate: '2050-01-01',
            pointColor: "#FF0036",
            info: null,
            status: 0,
            fa_id: 0,
            formData: {},
            list: [],
            month: "",
            selectedTime: '07:00', // 默认时间为早上 7 点
            today: todayStr,
            startDateToday: todayStr
        };
    },
    watch: {
        currentDayIn(val) {
            let diff = moment(this.currentDate).diff(moment(val), "days");
            if (diff < 0 || diff > 2) {
                this.status = 0;
            } else {
                this.status = 1;
            }
        },
        modelValue: {
            immediate: true,
            handler: function(val) {
                if (val) {
                    this.timeVal = val.split(' ')[1].split(':').map(v => parseInt(v))
                    this.selectedTime = val.split(' ')[1];
                    console.log(this.timeVal)
                }
            }
        }
    },

    created: function() {
        this.initTime();
    },


    methods: {
        confirm() {
            const val = this.currentDayIn + ' ' + this.selectedTime
            setTimeout(() => {
                this.$emit('input', val)
                this.$emit('update:modelValue', val)
            })
            this.$refs.popup.close()
        },

        changeTime(e) {
            this.selectedTime = e.detail.value.map(v => {
                return v < 9 ? '0' + v : v
            }).join(':')
        },

        open() {
            this.$refs.popup.open()
        },

        initTime: function() {
            if (this.currentDayIn == '') {
                var dateObj = new Date();
                this.cYear = Number(dateObj.getFullYear());
                this.cMonth = Number(dateObj.getMonth() + 1);
                this.cMonthStr = this.cMonth < 10 ? '0' + this.cMonth : this.cMonth;
                this.cDay = dateObj.getDate();
                this.cDay = this.cDay < 10 ? '0' + this.cDay : this.cDay;
                this.currentDate = this.cYear + '-' + this.cMonthStr + '-' + this.cDay;
                this.currentDayIn = this.cYear + '-' + this.cMonthStr + '-' + this.cDay;
                this.changeMonth();
            } else {
                var dates = this.currentDayIn.split(' ');
                if (!dates[1]) {
                    dates[1] = '07:00'; // 设置默认时间为早上 7 点
                }
                var dayArr = dates[0].split('-');
                this.cYear = Number(dayArr[0]);
                this.cMonth = dayArr[1];
                this.cDay = dayArr[2];
                var reg = new RegExp('^0[0-9]+$');
                if (reg.test(this.cMonth)) {
                    this.cMonth = this.cMonth.substr(1, 1);
                }
                this.cMonth = Number(this.cMonth);
                this.cMonthStr = this.cMonth < 10 ? '0' + this.cMonth : this.cMonth;
                this.currentDayIn = dates[0];
                this.currentTimeIn = dates[1];
                this.changeMonth();
            }
        },
        changeMonth: function() {
            this.cMonth = parseInt(this.currentDayIn.substring(5, 7));
            if (this.month == this.currentDayIn.substring(0, 7)) return;
            var daysList = [];
            var days = this.getDaysInOneMonth();
            var startWeek = this.getDay();
            var forSteps = 0;
            for (var i = (0 - startWeek); i < days; i++) {
                if (i >= 0) {
                    daysList[forSteps] = {
                        date: i >= 9 ? i + 1 : '0' + (i + 1),
                        nl: ''
                    };
                    daysList[forSteps].nl = guiCalendar.getLunarInfo(this.cYear, this.cMonth, i + 1);
                } else {
                    daysList[forSteps] = '';
                }
                forSteps++;
            }
            this.cMonthStr = this.cMonth < 10 ? '0' + this.cMonth : this.cMonth;
            this.days = daysList;
        },

        getDaysInOneMonth: function() {
            var d = new Date(this.cYear, this.cMonth, 0);
            return d.getDate();
        },
        getDay: function() {
            var d = new Date(this.cYear, this.cMonth - 1, 0);
            return d.getDay();
        },
        selectDate: function(e) {
            const selectedDate = e.detail.value;
            if (selectedDate >= this.today) {
                this.currentDayIn = selectedDate;
                this.changeMonth();
                this.timeVal = [7, 0]; // 选择日期时重置时间为早上 7 点
                this.selectedTime = '07:00';
            }
        },
        chooseDate: function(sedDate) {
            if (sedDate >= this.today) {
                this.currentDayIn = sedDate;
                this.timeVal = [7, 0]; // 选择日期时重置时间为早上 7 点
                this.selectedTime = '07:00';
            }
        },

        gotoToday: function() {
            var dateObj = new Date();
            this.cYear = Number(dateObj.getFullYear());
            this.cMonth = Number(dateObj.getMonth() + 1);
            this.cMonthStr = this.cMonth < 10 ? '0' + this.cMonth : this.cMonth;
            this.cDay = dateObj.getDate();
            this.cDay = this.cDay < 10 ? '0' + this.cDay : this.cDay;
            this.currentDayIn = this.cYear + '-' + this.cMonthStr + '-' + this.cDay;
            this.changeMonth();
            this.timeVal = [7, 0]; // 返回今天时重置时间为早上 7 点
            this.selectedTime = '07:00';
        },
        prevMonth: function() {
            this.cMonth--;
            if (this.cMonth < 1) {
                this.cMonth = 12;
                this.cYear--;
            }
            this.cMonthStr = this.cMonth < 10 ? '0' + this.cMonth : this.cMonth;
            const today = new Date();
            const currentYear = today.getFullYear();
            const currentMonth = today.getMonth() + 1;
            const currentDay = today.getDate();

            const prevMonthLastDay = new Date(this.cYear, this.cMonth, 0).getDate();
            const prevMonthDate = new Date(this.cYear, this.cMonth - 1, currentDay);

            if (prevMonthDate <= today) {
                this.currentDayIn = `${this.cYear}-${this.cMonthStr}-${String(currentDay).padStart(2, '0')}`;
            } else {
                this.currentDayIn = `${this.cYear}-${this.cMonthStr}-01`;
            }
            this.changeMonth();
        },
        nextMonth: function() {
            this.cMonth++;
            if (this.cMonth > 12) {
                this.cMonth = 1;
                this.cYear++;
            }
            this.cMonthStr = this.cMonth < 10 ? '0' + this.cMonth : this.cMonth;
            this.currentDayIn = `${this.cYear}-${this.cMonthStr}-01`;
            this.changeMonth();
        }
    }
}
</script>

<style>
.picker-column {
    height: 36px;
    line-height: 36px;
    text-align: center;
}

.gui-schedule-wrap {
    width: 100%;
}

.gui-schedule-header-date {
    height: 88rpx;
    line-height: 88rpx;
    font-size: 28rpx;
}

.gui-schedule-7item {
    width: 98rpx;
    margin-bottom: 22rpx;
    position: relative;
}

.gui-schedule-weeks {
    width: 98rpx;
    height: 88rpx;
    font-size: 26rpx;
    line-height: 88rpx;
    text-align: center;
}

.gui-date-ditems {
    width: 82rpx;
    height: 82rpx;
    border-radius: 80rpx;
}

.gui-date-day {
    height: 32rpx;
    line-height: 32rpx;
    text-align: center;
    font-size: 28rpx;
}

.gui-date-nl {
    height: 24rpx;
    line-height: 26rpx;
    font-size: 20rpx;
    text-align: center;
}

.gui-schedule-line {
    height: 20rpx;
    border-color: #F8F8F8;
}

.gui-schedule-time-list {
    margin-top: 20rpx;
}

.gui-schedule-timer {
    width: 88rpx;
    font-size: 22rpx;
    line-height: 36rpx;
}

.gui-schedule-body {
    width: 200rpx;
    flex: 1;
    margin-top: 15rpx;
}

.gui-schedules {
    padding: 10rpx;
    line-height: 30rpx;
    font-size: 22rpx;
    margin-top: 15rpx;
    border-radius: 8rpx;
}

.gui-schedule-time-list-wrap {
    padding: 20rpx;
}

.gui-schedule-today {
    line-height: 50rpx;
    height: 50rpx;
    font-size: 22rpx;
    padding-left: 20rpx;
    padding-right: 20rpx;
}

.gui-schedule-point {
    width: 18rpx;
    height: 18rpx;
    border-radius: 10rpx;
    background-color: #FF0036;
    position: absolute;
    right: 6rpx;
    top: 6rpx;
}

.gui-disabled-date {
    background-color: #e0e0e0;
    /* 变灰背景色 */
}

.gui-disabled-date-text {
    color: #999;
    /* 变灰文字颜色 */
}
</style>    